qype.API = {
	/**
	 * NOTE: In order to use the app
	 * you must apply for an API key from http://www.qype.co.uk/developers/api
	 * and paste the key below
	 */
    API_KEY: "PASTE YOUR API KEY HERE",

    /**
     * Common function to fetch data from the Qype API. Takes care of setting the
     * needed HTTP headers etc.
     *
     * Examples:
     *      qype.API.get("places")
     *      qype.API.get("places",
     *                   {
     *                     "onSuccess": function() {},
     *                     "onFailure": function() {}
     *                   },
     *                   "42",
     *                   { "foo": 1 })
     * 
     * @param {String} target The target Qype API command (e.g. "places")
     * @param {Object} callbacks Callbacks, should contain at least
     *                 onSuccess and onFailure callbacks. (optional)
     * @param {String} path Path to be appended to the base url (e.g. "42") (optional)
     * @param {Object} params Parameters to be appended to the url (optional)
     */
    get: function(target, callbacks, path, params) {

        params = params || {};
        params.consumer_key = this.API_KEY

        callbacks = callbacks || this.defaultCallbacks;

	    var xhr;
        var url = "http://api.qype.com/v1/" + target + (path ? ("/"+path) : "") + "?" + $.param(params);
	    xhr = new XMLHttpRequest();
	    xhr.open("GET", url, true);
	    xhr.setRequestHeader("Cache-Control", "no-cache");
	    xhr.setRequestHeader("Pragma", "no-cache");
	    xhr.setRequestHeader("Accept", "application/json");
	    xhr.setRequestHeader("Accept-Language", qype.strings.language);
	    xhr.onreadystatechange = function(){
	        if (xhr.readyState == 4) {
	            if (xhr.status == 200) {
	                if (xhr.responseText != null) {
						// Work with the response
	                    callbacks.onSuccess($.parseJSON(xhr.responseText));
	                }
	                else {
	                    callbacks.onFailure(xhr.responseText, xhr.status);
	                    return '';                    
	                }
	            }
	            else {
                    callbacks.onFailure(xhr.responseText, xhr.status);
	                return '';
	            }
	        }
	    }    
	    //send the request
	    xhr.send(null);
    },

    defaultCallbacks: {
        onSuccess: function(response) {
            util.log("{Qype.API} onSuccess:");
            util.log(response);
        },

        onFailure: function(response) {
            util.log("{Qype.API} onFailure:");
            util.log(response);
        }
    }
};